//
//  NSData+Sec.m
//  Yunxiaoyuan
//
//  Created by Liu Zhen on 3/25/15.
//  Copyright (c) 2015 LiuZhen. All rights reserved.
//

#import "NSData+Sec.h"
#import <CommonCrypto/CommonCrypto.h>

@implementation NSData (Sec)

- (NSData *)ECB3DESEncryptByKey:(NSData *)key {
    
    size_t numBytesEncrypted = 0;
    size_t bufferSize = self.length + kCCBlockSize3DES;
    void *buffer = malloc(bufferSize);
    
    CCCryptorStatus result = CCCrypt( kCCEncrypt, kCCAlgorithm3DES, kCCOptionPKCS7Padding|kCCOptionECBMode,
                                     key.bytes, kCCKeySize3DES,
                                     NULL,
                                     self.bytes, self.length,
                                     buffer, bufferSize,
                                     &numBytesEncrypted);
    NSData *output = [NSData dataWithBytes:buffer length:numBytesEncrypted];
    free(buffer);
    if( result == kCCSuccess ) {
        return output;
    }
    else {
        NSLog(@"Failed DES encrypt...");
        return nil;
    }
}

- (NSData *) ECB3DESDecryptByKey:(NSData *)key {
    
    //解密
    size_t numBytesDecrypted = 0;
    size_t bufferSize = self.length + kCCBlockSizeDES;
    void *buffer_decrypt = malloc(bufferSize);
    CCCryptorStatus result = CCCrypt( kCCDecrypt , kCCAlgorithm3DES, kCCOptionPKCS7Padding|kCCOptionECBMode,
                                     key.bytes, kCCKeySize3DES,
                                     NULL,
                                     self.bytes, self.length,
                                     buffer_decrypt, bufferSize,
                                     &numBytesDecrypted );
    
    NSData *output = [NSData dataWithBytes:buffer_decrypt length:numBytesDecrypted];
    free(buffer_decrypt);
    if( result == kCCSuccess ) {
        return output;
    }
    else {
        NSLog(@"Failed DES decrypt ...");
        return nil;
    }
}

+ (NSData *)genernate3DESKeyWithString:(NSString *)string {

    static NSData *secKey = nil;
    
    if (!secKey) {

        //预处理密钥
        char keyPtr[kCCKeySize3DES];
        bzero(keyPtr, sizeof(keyPtr));
        NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
        [data getBytes:keyPtr length:sizeof(keyPtr)];
        secKey = [NSData dataWithBytes:keyPtr length:sizeof(keyPtr)];
    }
    
    return secKey;
}

@end
